package com.cosytek.farmmanager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.cosytek.farmmanager.data.Farm;
import com.cosytek.farmmanager.data.FarmSummary;
import com.cosytek.farmmanager.data.Main;
import com.cosytek.farmmanager.data.TaskSummary;

/**
 * Created by Happy on 2015/4/20.
 */
public class FarmFragmentTaskAdapter extends BaseAdapter {

    private static final String TAG = "MainFragmentFarmAdapter";

    public FarmFragmentTaskAdapter(Main main, String farmId, LayoutInflater inflater) {
        viewInflater = inflater;
        this.main = main;
        this.farmId = farmId;
    }

    private final LayoutInflater viewInflater;
    private String farmId;
    private Main main;

    @Override
    public int getCount() {
        Farm f = main.getFarm(farmId);
        int count =  f.getTaskCount();
        return count;
    }

    @Override
    public Object getItem(int position) {
        Farm f = main.getFarm(farmId);
        if (f == null) {
            return 0;
        }
        TaskSummary ts = f.getTaskSummary(position);

        return ts;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        if (convertView == null) {
            convertView = viewInflater.inflate(R.layout.frag_task_list_item, null);
            vh = new ViewHolder();
            vh.viewTaskName = (TextView)convertView.findViewById(R.id.frag_task_list_item_task_name);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder)convertView.getTag();
        }

        Farm f = main.getFarm(farmId);
        TaskSummary ts = f.getTaskSummary(position);
        if (ts != null) {
            vh.viewTaskName.setText(ts.getName());
        }

        return convertView;
    }

    public void invalidate() {
        notifyDataSetChanged();
    }

    public void updateData(Main main, String farmId) {
        this.main = main;
        this.farmId = farmId;
        invalidate();
    }

    private class ViewHolder {
        public TextView viewTaskName;
    }
}
